<?php
require 'db.php';
require 'vendor/autoload.php'; // 引入 Composer 自动加载器
include_once 'secret/jwt.php';

use Firebase\JWT\JWT;
use Firebase\JWT\Key;

// 获取 JWT
if (!isset($_COOKIE['token'])) {
    header('Location: index.php');
    exit();
}

$jwt = $_COOKIE['token'];

try {
    $decoded = JWT::decode($jwt, new Key($secretKey, 'HS256'));
    $user_id = $decoded->data->id;
} catch (Exception $e) {
    echo json_encode(['error' => '无效的令牌: ' . $e->getMessage()]);
    exit();
}

if (isset($_POST['article_id'])) {
    $article_id = $_POST['article_id'];

    // 检查是否已经收藏过
    $checkSql = "SELECT * FROM favorites WHERE user_id = ? AND article_id = ?";
    $checkStmt = $conn->prepare($checkSql);
    $checkStmt->bind_param("ii", $user_id, $article_id);
    $checkStmt->execute();
    $checkResult = $checkStmt->get_result();

    if ($checkResult->num_rows > 0) {
        echo json_encode(["error" => "您已经收藏过这篇文章"]);
    } else {
        $sql = "INSERT INTO favorites (user_id, article_id) VALUES (?, ?)";
        $stmt = $conn->prepare($sql);
        $stmt->bind_param("ii", $user_id, $article_id);

        if ($stmt->execute()) {
            echo json_encode(["message" => "收藏成功"]);
        } else {
            echo json_encode(["error" => "收藏失败"]);
        }

        $stmt->close();
    }

    $checkStmt->close();
}    
?>